package com.shengyuan.manage_os.old.ying.boce.jsy;

import com.baidu.mapapi.common.SysOSUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.shengyuan.manage_os.old.ying.boce.task.GenericTask;
import com.shengyuan.manage_os.old.ying.boce.task.TaskParams;
import com.shengyuan.manage_os.old.ying.boce.task.TaskResult;
import com.shengyuan.manage_os.old.ying.erpm.Actual_System_Setting;
import com.shengyuan.manage_os.old.ying.erpm.LoginActivity;
import com.shengyuan.manage_os.old.ying.erpm.MainApplication;
import com.shengyuan.manage_os.old.ying.erpm.db.Actual_Data_Table;
import com.shengyuan.manage_os.old.ying.erpm.db.CLS_Actual_Data_Table;
import com.shengyuan.manage_os.old.ying.erpm.util.Utility;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
//import android.renderscript.ProgramFragmentFixedFunction.Builder.Format;


@SuppressLint("HandlerLeak")
public class MobileHandlerTask extends GenericTask{
	public static  MobileHandlerTask pMobileHandlerTask;
	public int  m_id, fujian_id , timeout = 120000;
	private CLS_Actual_Data_Table cls_Data;
	private boolean stop ;
	private long iStep;
	
	private long time_1, time_2, steptime;
	private int state1, state2;
	
	private Handler uiHandler1 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(stop) return;
			if (msg.what==1 && Utility.isOpenNetwork()) {
				try {
					//time_1 = CurrentTime.getTime().getTime();
					SendData();
				} catch (Exception e) {
				}
			}else {
				StartTime(uiHandler1);
			}
		}
	};
	
	private Handler uiHandler2 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(stop) return;
			if (msg.what==1 && Utility.isOpenNetwork() && Utility.isExistExternalStore()) {
				try {					
					//time_2 = CurrentTime.getTime().getTime();
					//if (GetJieYue()) {
//					if(true){
						SendPicFuJian();
//					}else  {
//						WifiManager mWifiManager = 
//								(WifiManager)ECApplication.Instance.getSystemService
//						 		(ECApplication.Instance.WIFI_SERVICE);
//						int mWifiState = mWifiManager.getWifiState();
//						if (mWifiState==mWifiManager.WIFI_STATE_ENABLED) {
//							//WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
//							DhcpInfo dhcpInfo = mWifiManager.getDhcpInfo();
//							if (dhcpInfo!=null ) {
//								//String s = Formatter.formatIpAddress( dhcpInfo.ipAddress);
//								SendPicFuJian();
//							}
//						}
//					}
					
				} catch (Exception e) {
				}
			}else {
				StartTime(uiHandler2);
			}
		}
	};
	
	public void start() {
		stop = false;
		steptime= 2;
		StartTime(uiHandler1);
		StartTime(uiHandler2);
		//uiHandler1.sendEmptyMessageDelayed(1, 10 * 1000);
		//uiHandler2.sendEmptyMessageDelayed(1, 10 * 1000);
	}
	
	public void Resume() {
//		stop = false;
//		long l = CurrentTime.getTime().getTime();
//		if ((l - time_1)>1000) {
//			if (uiHandler1!=null) {
//				uiHandler1.sendEmptyMessageDelayed(1, 10 * 1000);
//			}
//		}
//		if ((l - time_2)>1000) {
//			if (uiHandler2!=null) {
//				uiHandler2.sendEmptyMessageDelayed(1, 10 * 1000);
//			}
//		}
	}
	
	public void stop(){
		//pMobileHandlerTask.setCancelable(true);
		stop = true;
	}

	private String Message = "";
	public String getMsg() {
		return Message;
	}


	public void SendData() {
		try {
			CLS_Actual_Data_Table cls = new CLS_Actual_Data_Table();
			Actual_Data_Table dbo = new Actual_Data_Table(MainApplication.Instance);
			//dbo.get_alllist("2");
			cls = dbo.get_Sended( "0" );
			m_id = cls.Id;
			dbo.close();
			if (m_id > 0 && state1==0) { //第一步 上传数据
				state1 = 1;
				final RequestParams params = new RequestParams();
	            params.put("action", "upload");
	            params.put("Id", cls.Id+"");
	            params.put("USER", cls.USER);
	            params.put("FORM_TYPE", cls.FORM_TYPE);
//				params.put("FORM_TYPE", "com.ying.erpm.Actual_OA_DaKa_JiDong");
	            params.put("JSON1", cls.JSON1);
	            params.put("JSON2", cls.JSON2 );
	            params.put("OVERTIME", cls.OVERTIME);
	            params.put("FINISHED", cls.FINISHED+"");
	            params.put("SENDED", cls.SENDED + "");
	            params.put("PRINTEABLED", cls.PRINTEABLED +"" );
	            params.put("PCOUNT", cls.PCOUNT +"");
	            params.put("SERVICEID", cls.SERVICEID +"");
//		            if (cls.mFilesLists!=null && cls.mFilesLists.length>0) {
//		            	params.put(cls.mFilesLists[0].getFilname(), cls.mFilesLists[0].getFile());
//					}
//		            ret = SocketHttpRequester.post(requestUrl, params, files);			
	            AsyncHttpClient client = new AsyncHttpClient();
	            client.setTimeout(timeout);
	            RequestHandle handle = client.post(APIErpm.getBaseURL(),params, new AsyncHttpResponseHandler(){

	            	private String mMessage ;
					@Override
					public void onStart() {
						super.onStart();
						Utility.MessageBox("数据上传");
						System.out.println("###########onStart========"+APIErpm.getBaseURL()+"??????"+params.toString());
					}

					@Override
					@Deprecated
					public void onSuccess(int statusCode, String content) {
						super.onSuccess(statusCode, content);
						if (statusCode==200 && content!=null && content.contains("ERPMOK") ) {
							Utility.MessageBox( m_id + " 已上传");
							Actual_Data_Table dbo = new Actual_Data_Table(MainApplication.Instance);
							dbo.Update_Data(m_id, dbo.SERVICEID, "1");
							dbo.close();
							steptime =3;
						}
					}

					@Override
					public void onFinish() {
						super.onFinish();
						state1 =0;
						if (steptime==10) {
//							Utility.MessageBox("网络状况不佳,"+mMessage);
						}else {
							Utility.MessageBox("数据上传完成");
							System.out.println("###########onFinish========");
						}
						StartTime(uiHandler1);
					}

					@Override
					@Deprecated
					public void onFailure(Throwable error) {
						System.out.println("###########onFailure========");
						steptime = 10;
						mMessage = error.getMessage();
						super.onFailure(error);
					}
	            });

				System.out.println("&&&&&&&&"+handle);
			}else {
				StartTime(uiHandler1);
			}
		} catch (Exception e) {
			System.out.println("###########Exception========"+e.toString());
			StartTime(uiHandler1);
		}
	}
	
	private void StartTime(Handler handler) {
		if (handler!=null) {
			handler.sendEmptyMessageDelayed(1, steptime * 1000);
		}
//		if (Actual_OA_DaKa_JiDong.bShow ) {
//			return;
//		}
//		if (iStep++> 600) {
//			iStep = 0 ;
//			long now =0;
//			Actual_Data_Table dbo = new Actual_Data_Table(ECApplication.Instance);
//			int i  = dbo.get_Sended_DaKa();
//			if (i <= 1) {
//				now = dbo.get_Sended_Last();
//				//2小时以上
//				long hour2 = now + (1000 *60)* 60 * 2;
//				if (hour2 > CurrentTime.getTime().getTime()  && Actual_OA_DaKa_JiDong.bShow==false ) {
//					Actual_OA_DaKa_JiDong jiDong = new Actual_OA_DaKa_JiDong();
//					jiDong.SetAlarmActivity(hour2 + 1000* 60);
//				}
//			}
//			dbo.close();
//		}
	}
	
	public void SendPicFuJian() {
		try {
			Actual_Data_Table dbo = new Actual_Data_Table(MainApplication.Instance);
			cls_Data = dbo.get_Sended( "1" );
			fujian_id = cls_Data.Id;
			dbo.close();
			if (fujian_id > 0 && state2 ==0) { //第二步 上传图片附件
				state2 = 1;
				final RequestParams params = new RequestParams();
	            params.put("action", "upload");
	            params.put("Id", cls_Data.Id+"");
	            params.put("USER", cls_Data.USER);
	            params.put("FORM_TYPE", cls_Data.FORM_TYPE);
//				params.put("FORM_TYPE", "com.ying.erpm.Actual_OA_DaKa_JiDong");
	            params.put("JSON1", cls_Data.JSON1);
	            params.put("JSON2", cls_Data.JSON2 );
	            params.put("OVERTIME", cls_Data.OVERTIME);
	            params.put("FINISHED", cls_Data.FINISHED+"");
	            params.put("SENDED", cls_Data.SENDED + "");
	            params.put("PRINTEABLED", cls_Data.PRINTEABLED +"" );
	            params.put("PCOUNT", cls_Data.PCOUNT +"");
	            params.put("SERVICEID", cls_Data.SERVICEID +"");

	            cls_Data.getFormFile_AllFile();
//				System.out.println("###########cls_Data.mFilesLists.length========"+cls_Data.mFilesLists.length);
	            if (cls_Data.mFilesLists!=null && cls_Data.mFilesLists.length>0) {
	            	params.put("FILE", cls_Data.mFilesLists[0].getFile().getAbsolutePath());
	            	params.put(cls_Data.mFilesLists[0].getFilname(), cls_Data.mFilesLists[0].getFile());
	            }else {
					dbo = new Actual_Data_Table(MainApplication.Instance);
					dbo.Update_Data(fujian_id, dbo.SERVICEID, "2");
					dbo.close();
					cls_Data.DeletePath();
					//uiHandler2.sendEmptyMessageDelayed(1, 10 * 1000);
					StartTime(uiHandler2);
					state2 = 0;
					return;
				}
	            
	            AsyncHttpClient client = new AsyncHttpClient();
	            client.setTimeout(timeout);
	            client.post(APIErpm.getBaseURL(),params, new AsyncHttpResponseHandler(){

					@Override
					public void onStart() {
						super.onStart();
						Utility.MessageBox("开始附件上传");
						System.out.println("###########onStart========"+APIErpm.getBaseURL()+"?"+params.toString());
					}

					@Override
					@Deprecated
					public void onSuccess(int statusCode, String content) {
						super.onSuccess(statusCode, content);
						if (statusCode==200 && content!=null && content.contains("ERPMOK") ) {
							try {
								Utility.MessageBox( cls_Data.OVERTIME +"\n" + cls_Data.mFilesLists[0].getFile().getName());
								if (cls_Data.mFilesLists.length>0 && cls_Data.mFilesLists[0]!=null) {
									cls_Data.mFilesLists[0].getFile().delete();	
								}					
								Utility.MessageBox("附件上传成功完成");

								System.out.println("###########onSuccess===@@@@@@====="+"====id==="+m_id);
							} catch (Exception e) {
							}
						}
					}

					@Override
					@Deprecated
					public void onFailure(Throwable error, String content) {
						super.onFailure(error, content);
						try {
							Utility.MessageBox(error.getMessage());
						} catch (Exception e) {
						}
					}

					@Override
					public void onFinish() {
						super.onFinish();
						state2 = 0 ;
//						Utility.MessageBox("附件上传结束");
						StartTime(uiHandler2);
						
						//uiHandler2.sendEmptyMessageDelayed(1, 10 * 1000);
					}
	            });
			}else {
				//uiHandler2.sendEmptyMessageDelayed(1, 10 * 1000);
				StartTime(uiHandler2);
			}
		} catch (Exception e) {
			StartTime(uiHandler2);
			Utility.MessageBox(e.getMessage());
		}
	}
	
	
	@Override
	protected TaskResult _doInBackground(TaskParams... params) {
		try {
	    	try {
	    		if (LoginActivity.pmUser ==null || LoginActivity.pmUser.ID==0)
					return TaskResult.CANCELLED;
	    		int id =0;
	    		
	    		CLS_Actual_Data_Table cls = new CLS_Actual_Data_Table();
	    		Actual_Data_Table dbo = new Actual_Data_Table(MainApplication.Instance);
	    		cls = dbo.get_Sended( "0" );
	    		id = cls.Id;
	    		dbo.close();
	    		if (id > 0) { //第一步 上传数据
	    			if(MainApplication.mApiErpm.UpLoadAllFilesAndData(cls))
	    			{
	    				dbo = new Actual_Data_Table(MainApplication.Instance);
	    				dbo.Update_Data(cls.Id, dbo.SERVICEID, "1");
	    				dbo.close();

						System.out.println("###########(MainApplication.mApiErpm.UpLoadAllFilesAndData======"+MainApplication.mApiErpm.UpLoadAllFilesAndData(cls));
	    			}
				}
				System.out.println("###########(MainApplication.mApiErpm.UpLoadAllFilesAndData======"+id);
	    		
	    		dbo = new Actual_Data_Table(MainApplication.Instance);
	    		cls = dbo.get_Sended( "1" );
	    		id = cls.Id;
	    		dbo.close();
	    		if ( id > 0 ) { //第二步 上传图片附件
	    			cls.getFormFile_AllFile();
	    			if (cls.mFilesLists!=null && cls.mFilesLists.length > 0) {
		    			if(MainApplication.mApiErpm.UpLoadAllFilesAndData(cls))
		    			{
		    				cls.mFilesLists[0].getFile().delete();
		    			}
					}else {
	    				dbo = new Actual_Data_Table(MainApplication.Instance);
	    				dbo.Update_Data(cls.Id, dbo.SERVICEID, "2");
	    				dbo.close();
					}
				}
			} catch (Exception e) {
				System.out.println("###########(MainApplication.mApiErpm.UpLoadAllFilesAndData@@@@@@@@@@@@@@@===="+e.toString());
				Message = e.getMessage();
				return TaskResult.CANCELLED;
			}
			return TaskResult.OK;
		} catch (Exception e) {
			Message = e.getMessage();
			return TaskResult.FAILED;
		}
	}
	
	private Boolean GetJieYue() {
		if (Actual_System_Setting.Instance!=null) {
			SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Actual_System_Setting.Instance); 
			return sp.getBoolean("title_form_setting_table_lixian", false); 			
		}else {
			return false;
		}
	}
	
	
//	private TaskListener mTaskListener = new TaskAdapter() {
//		@Override
//		public void onPostExecute(GenericTask task, TaskResult result) {
//			int delayed = 10;
//			MobileHandlerTask t = (MobileHandlerTask)task;
//			if (result == TaskResult.OK) {
//				
//			} if (result == TaskResult.CANCELLED) {
//				
//			} else {
//				//Utility.MessageBox(t.getMsg());
//				delayed = 10;
//			}
//			uiHandler1.sendEmptyMessageDelayed(1, delayed * 1000);
//		}
//
//		@Override
//		public void onCancelled(GenericTask task) {
//		}
//
//		@Override
//		public void onPreExecute(GenericTask task) {
//		}
//	};		
}
